package com.seadragon.app.ksr.validator;

import static com.seadragon.app.ksr.model.KsrConstants.DEFAULT_MESSAGE_KEY_INVALID_EMAIL;
import static com.seadragon.app.ksr.model.KsrConstants.ERROR_MESSAGE_KEY_FIELD_REQUIRED;
import static com.seadragon.app.ksr.model.KsrConstants.ERROR_MESSAGE_KEY_INVALID_EMAIL;
import static com.seadragon.app.ksr.model.KsrConstants.FIELD_NAME_EMAIL;
import static com.seadragon.app.ksr.model.KsrConstants.FIELD_NAME_PHONE_NUMBER;
import static com.seadragon.app.ksr.model.KsrConstants.FIELD_NAME_SPECIALTY;

import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.seadragon.app.ksr.model.Address;
import com.seadragon.app.ksr.model.Office;

public class OfficeValidator implements Validator {
	private final Validator addressValidator;
	public OfficeValidator(Validator addressValidator) {
        if (addressValidator == null) {
            throw new IllegalArgumentException(
              "The supplied [Validator] is required and must not be null.");
        }
        if (!addressValidator.supports(Address.class)) {
            throw new IllegalArgumentException(
              "The supplied [Validator] must support the validation of [Address] instances.");
        }
        this.addressValidator = addressValidator;
	}	
//	@Override
	public boolean supports(Class<?> clazz) {
		return Office.class.isAssignableFrom(clazz);
	}

//	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, FIELD_NAME_PHONE_NUMBER, ERROR_MESSAGE_KEY_FIELD_REQUIRED);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, FIELD_NAME_SPECIALTY, ERROR_MESSAGE_KEY_FIELD_REQUIRED);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, FIELD_NAME_EMAIL, ERROR_MESSAGE_KEY_FIELD_REQUIRED);
		EmailValidator emailValidator = EmailValidator.getInstance();
		Office office = (Office) target;
		if(office.getEmailAddress() != null && office.getEmailAddress().length() > 0 && !emailValidator.isValid(office.getEmailAddress())){
			errors.rejectValue(FIELD_NAME_EMAIL, ERROR_MESSAGE_KEY_INVALID_EMAIL, DEFAULT_MESSAGE_KEY_INVALID_EMAIL);
		}		
        try {
            errors.pushNestedPath("address");
            ValidationUtils.invokeValidator(this.addressValidator, office.getAddress(), errors);
        } finally {
            errors.popNestedPath();
        }			
	}

}
